import { useState, useEffect, useCallback } from 'react';
import { getProductList, deleteProduct, getImageUrl } from '../services/pocketBaseService';
import ProductForm from './ProductForm';
import { useAuth } from '../contexts/AuthContext';

function ProductList() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [showForm, setShowForm] = useState(false);
  const [editingProduct, setEditingProduct] = useState(null);
  const [filters, setFilters] = useState({
    productName: '',
    status: ''
  });
  const { user } = useAuth();

  // 防抖函数
  const debounce = (func, wait) => {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  };

  // 加载商品列表
  const loadProducts = async () => {
    setLoading(true);
    setError('');
    console.log('加载商品列表111',user);
    try {
      const result = await getProductList(page, 10, {
        productName: filters.productName,
        status: filters.status === '' ? undefined :  true,
        belongto_store: user && user.store ? user.store.id : undefined
      });
      if (result.success) {
        setProducts(result.data.items);
        setTotalPages(result.data.totalPages || 1);
      } else {
        setError('获取商品列表失败: ' + result.error);
      }
    } catch (err) {
      setError('获取商品列表时发生错误');
      console.error('获取商品列表错误:', err);
    } finally {
      setLoading(false);
    }
  };

  // 使用 useCallback 和防抖优化加载函数
  const debouncedLoadProducts = useCallback(
    debounce(loadProducts, 500), // 500ms 防抖延迟
    [page, filters, user]
  );

  // 首次加载和筛选条件变更时重新加载数据
  useEffect(() => {
    debouncedLoadProducts();
  }, [page, filters, debouncedLoadProducts]);

  // 处理筛选条件变更
  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters(prev => ({
      ...prev,
      [name]: value
    }));
    setPage(1); // 重置到第一页
  };

  // 处理删除商品
  const handleDelete = async (id) => {
    if (window.confirm('确定要删除这个商品吗？')) {
      try {
        const result = await deleteProduct(id);
        if (result.success) {
          loadProducts(); // 重新加载列表
        } else {
          alert('删除失败: ' + result.error);
        }
      } catch (err) {
        console.error('删除商品错误:', err);
        alert('删除商品时发生错误');
      }
    }
  };

  // 编辑商品
  const handleEdit = (product) => {
    setEditingProduct(product);
    setShowForm(true);
  };

  // 添加新商品
  const handleAdd = () => {
    setEditingProduct(null);
    setShowForm(true);
  };

  // 表单提交后的回调
  const handleFormSubmit = () => {
    setShowForm(false);
    loadProducts(); // 重新加载列表
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <h2 className="text-2xl font-bold mb-6">商品管理</h2>

      {/* 筛选表单 */}
      <div className="bg-white shadow rounded-lg p-4 mb-6">
        <h3 className="text-lg font-medium mb-3">筛选条件</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700">商品名称</label>
            <input
              type="text"
              name="productName"
              value={filters.productName}
              onChange={handleFilterChange}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">状态</label>
            <select
              name="status"
              value={filters.status}
              onChange={handleFilterChange}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            >
              <option value="">全部</option>
              <option value="true">已上架</option>
              <option value="false">已下架</option>
            </select>
          </div>
          <div className="flex items-end">
            <button
              onClick={() => {
                // 手动查询时直接调用，不使用防抖
                loadProducts();
              }}
              className="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              查询
            </button>
          </div>
        </div>
      </div>

      {/* 操作按钮 */}
      <div className="mb-4">
        <button
          onClick={handleAdd}
          className="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
        >
          添加商品
        </button>
      </div>

      {/* 商品列表 */}
      {loading ? (
        <div className="text-center py-4">加载中...</div>
      ) : error ? (
        <div className="text-center py-4 text-red-500">{error}</div>
      ) : (
        <div className="shadow overflow-x-auto border-b border-gray-200 sm:rounded-lg">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-24">
                  图片
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  商品名称
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  描述
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  积分
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  现金价格
                </th>
                <th scope="col" className="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  售出/库存
                </th>
                <th scope="col" className="px-8 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  销售策略
                </th>

                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {products.length === 0 ? (
                <tr>
                  <td colSpan="8" className="px-6 py-4 text-center text-sm text-gray-500">
                    暂无商品数据
                  </td>
                </tr>
              ) : (
                products.map((product) => (
                  <tr key={product.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center justify-center">
                        {product.image_file ? (
                          <div className="relative">
                            <img
                              src={getImageUrl(null, product.id, product.image_file)}
                              alt={product.product_name}
                              className="h-20 w-20 object-cover rounded shadow-sm border border-gray-200"
                              onError={(e) => {
                                e.target.style.display = 'none';
                                e.target.nextSibling.style.display = 'flex';
                              }}
                              onLoad={(e) => {
                                e.target.style.opacity = '1';
                              }}
                              style={{ opacity: 0, transition: 'opacity 0.3s' }}
                            />
                            <div className={`h-20 w-20 bg-gray-200 rounded flex items-center justify-center text-xs text-gray-500 border border-gray-200 ${product.image_file ? 'hidden' : ''}`}>
                              无图
                            </div>
                          </div>
                        ) : (
                          <div className="h-20 w-20 bg-gray-200 rounded flex items-center justify-center text-xs text-gray-500 border border-gray-200">
                            无图
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">{product.product_name}</div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-500 max-w-xs truncate">{product.product_desc}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">{product.points_score}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">¥{product.cash_price}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900"> {product.sold} /{product.stock} </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">
                        {product.sold_strategy}{product.sold_strategy === "只需积分" ? "" : `+${product.sold_strategy_num} 元`}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        product.status ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                      }`}>
                        {product.status ? '已上架' : '已下架'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <button
                        onClick={() => handleEdit(product)}
                        className="text-indigo-600 hover:text-indigo-900 mr-4"
                      >
                        编辑
                      </button>
                      <button
                        onClick={() => handleDelete(product.id)}
                        className="text-red-600 hover:text-red-900"
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* 分页 */}
      {!loading && products.length > 0 && (
        <div className="flex justify-between items-center mt-4">
          <div className="text-sm text-gray-700">
            当前第 <span className="font-medium">{page}</span> 页
            {totalPages > 0 && <span>, 共 <span className="font-medium">{totalPages}</span> 页</span>}
          </div>
          <div>
            <button
              onClick={() => setPage((prev) => Math.max(prev - 1, 1))}
              disabled={page === 1}
              className={`relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white ${
                page === 1 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-50'
              } mr-3`}
            >
              上一页
            </button>
            <button
              onClick={() => setPage((prev) => (prev < totalPages ? prev + 1 : prev))}
              disabled={page >= totalPages}
              className={`relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white ${
                page >= totalPages ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-50'
              }`}
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* 商品表单弹窗 */}
      {showForm && (
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <div className="p-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-bold">
                  {editingProduct ? '编辑商品' : '添加商品'}
                </h3>
                <button
                  onClick={() => setShowForm(false)}
                  className="text-gray-500 hover:text-gray-700"
                >
                  <span className="text-2xl">&times;</span>
                </button>
              </div>
              <ProductForm
                product={editingProduct}
                onSuccess={handleFormSubmit}
                onCancel={() => setShowForm(false)}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default ProductList;